package at.fhj.itm11.forum.data.impl;

import java.util.List;

import javax.ejb.Stateless;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import at.fhj.itm11.forum.data.TopicDAO;
import at.fhj.itm11.forum.model.Topic;

/**
 * @author Mario Kullnigg
 * @author Jürgen Kiendler
 **/

@Named
@Stateless
public class TopicDAOImpl implements TopicDAO {

	@Inject
	private EntityManager em;
	
	@Inject
	private Event<Topic> topicEventSrc;

	public Topic findById(Long id) {
		return em.find(Topic.class, id);
	}

	public List<Topic> retrieveAllTopicsOrderedByTitle() {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Topic> criteria = cb.createQuery(Topic.class);
		Root<Topic> topic = criteria.from(Topic.class);
		criteria.select(topic).orderBy(cb.asc(topic.get("title")));
		return em.createQuery(criteria).getResultList();
	}

	public void register(Topic topic) {
		em.persist(topic);
		topicEventSrc.fire(topic);
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}
	
	public void setTopicEventSrc(Event<Topic> topicEventSrc) {
		this.topicEventSrc = topicEventSrc;
	}
}
